package com.jcfk.eam.service.main;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.exception.CustomException;
import com.jcfk.common.core.exception.OptimisticLockerException;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.main.EamAssetInfoDao;
import com.jcfk.eam.dao.mould.MouldAssetInfoDao;
import com.jcfk.eam.domain.dto.main.AssetChangeInfoDTO;
import com.jcfk.eam.domain.dto.main.EamAssetInfoDTO;
import com.jcfk.eam.domain.dto.main.EamAssetPictureDTO;
import com.jcfk.eam.domain.dto.mould.EamAssetMouldProductDTO;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.po.mould.EamAssetMouldProduct;
import com.jcfk.eam.domain.po.mould.EamMouldPackageInfo;
import com.jcfk.eam.domain.query.main.EamAssetInfoQuery;
import com.jcfk.eam.domain.query.main.EamAssetPictureQuery;
import com.jcfk.eam.domain.query.mould.EamAssetMouldProductQuery;
import com.jcfk.eam.domain.uploadExcel.main.EamAssetInfoUploadExcel;
import com.jcfk.eam.enums.AssetKind;
import com.jcfk.eam.service.base.EamCustomService;
import com.jcfk.eam.service.mould.EamAssetMouldProductService;
import com.jcfk.eam.service.mould.EamMouldPackageInfoService;
import com.jcfk.system.domain.dto.SysAnnexesFileDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 资产台账
 *
 * @author libinghai
 * @email 35738025@gqq.com
 * @date 2024-07-28
 */
@Service
public class EamAssetInfoService extends BaseService<EamAssetInfoDao, EamAssetInfo> {

    @Autowired
    private EamAssetPictureService eamAssetPictureService;

    @Autowired
    private MouldAssetInfoDao mouldAssetInfoDao;

    @Autowired
    private EamCustomService eamCustomService;
    @Autowired
    private EamAssetMouldProductService eamAssetMouldProductService;
    @Autowired
    private EamMouldPackageInfoService eamMouldPackageInfoService;

    /**
     * EamAssetInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamAssetInfoDTO> queryByPage(DataPage<EamAssetInfoDTO> page, EamAssetInfoQuery query) {
        // 分页查询
        query.setAssetCode(StringUtils.isEmpty(query.getAssetCode()) ? query.getAssetCode() : "%" + query.getAssetCode() + "%");
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : "%" + query.getAssetName() + "%");
        query.setSearchAssetInfo(StringUtils.isEmpty(query.getSearchAssetInfo()) ? query.getSearchAssetInfo() : "%" + query.getSearchAssetInfo() + "%");
        query.setAssetTypeId(StringUtils.isEmpty(query.getAssetTypeId()) ? query.getAssetTypeId() : query.getAssetTypeId() + "%");
        query.setLocationId(StringUtils.isEmpty(query.getLocationId()) ? query.getLocationId() : "%" + query.getLocationId() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * EamAssetInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamAssetInfoDTO> queryMouldByPage(DataPage<EamAssetInfoDTO> page, EamAssetInfoQuery query) {
        // 分页查询
        query.setAssetCode(StringUtils.isEmpty(query.getAssetCode()) ? query.getAssetCode() : "%" + query.getAssetCode() + "%");
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : "%" + query.getAssetName() + "%");
        query.setSearchAssetInfo(StringUtils.isEmpty(query.getSearchAssetInfo()) ? query.getSearchAssetInfo() : "%" + query.getSearchAssetInfo() + "%");
        query.setAssetTypeId(StringUtils.isEmpty(query.getAssetTypeId()) ? query.getAssetTypeId() : query.getAssetTypeId() + "%");
        query.setLocationId(StringUtils.isEmpty(query.getLocationId()) ? query.getLocationId() : "%" + query.getLocationId() + "%");
        page = this.mouldAssetInfoDao.queryByPage(page, query);
        return page;
    }

    public List<EamAssetInfoDTO> queryByPage(EamAssetInfoQuery query) {
        // 分页查询
        query.setAssetCode(StringUtils.isEmpty(query.getAssetCode()) ? query.getAssetCode() : query.getAssetCode() + "%");
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : query.getAssetName() + "%");
        return this.baseMapper.queryByPage(query);
    }

    /**
     * 判断EamAssetInfo是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamAssetInfoDTO dto) {
        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入资产台账
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamAssetInfoDTO dto) {
        List<EamAssetPictureDTO> attachDTOS = new ArrayList<>();

        // 保存
        EamAssetInfo item = new EamAssetInfo();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        item.setId(IdUtils.newId());

        // 添加检查记录图片
        Integer recordIndex = 1;
        if (dto.getAssetPhotos() != null) {
            for (SysAnnexesFileDTO annexesFile : dto.getAssetPhotos()) {
                EamAssetPictureDTO attachDTO = new EamAssetPictureDTO();

                attachDTO.setId(IdUtils.newId());
                attachDTO.setAssetId(item.getId());
                attachDTO.setSort(recordIndex);
                attachDTO.setFileType(annexesFile.getFileType());
                attachDTO.setPath(annexesFile.getPath());
                attachDTO.setOriginalFilename(annexesFile.getOriginalfilename());
                attachDTO.setFileName(annexesFile.getFilename());
                attachDTO.setUrl(annexesFile.getUrl());

                attachDTOS.add(attachDTO);

                recordIndex++;
            }
        }
        List<EamAssetMouldProduct> products = new ArrayList<>();
        if (CollUtil.isNotEmpty(dto.getProducts())) {
            products = dto.getProducts().stream()
                    .map(product -> {
                        EamAssetMouldProduct eamAssetMouldProduct = BeanUtil.copyProperties(product, EamAssetMouldProduct.class);
                        eamAssetMouldProductService.setDefaultValue(eamAssetMouldProduct);
                        eamAssetMouldProduct.setAssetId(item.getId());
                        return eamAssetMouldProduct;
                    }).collect(Collectors.toList());
        }

        super.save(item);

        // 保存附件表
        eamAssetPictureService.save(attachDTOS);

        eamCustomService.saveEamCustoms(dto.getCustoms(), item.getId(), item.getAssetKind());

        if (CollUtil.isNotEmpty(products)) eamAssetMouldProductService.saveBatch(products);
    }

    /**
     * 更新资产台账
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamAssetInfoDTO dto) {

        List<EamAssetPictureDTO> attachDTOS = new ArrayList<>();

        // 保存
        EamAssetInfo item = new EamAssetInfo();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        // 添加检查记录图片
        Integer recordIndex = 1;
        if (dto.getAssetPhotos() != null) {
            for (SysAnnexesFileDTO annexesFile : dto.getAssetPhotos()) {
                EamAssetPictureDTO attachDTO = new EamAssetPictureDTO();

                attachDTO.setId(IdUtils.newId());
                attachDTO.setAssetId(item.getId());
                attachDTO.setSort(recordIndex);
                attachDTO.setFileType(annexesFile.getFileType());
                attachDTO.setPath(annexesFile.getPath());
                attachDTO.setOriginalFilename(annexesFile.getOriginalfilename());
                attachDTO.setFileName(annexesFile.getFilename());
                attachDTO.setUrl(annexesFile.getUrl());

                attachDTOS.add(attachDTO);

                recordIndex++;
            }
        }
        List<EamAssetMouldProduct> products = new ArrayList<>();
        if (CollUtil.isNotEmpty(dto.getProducts())) {
            products = dto.getProducts().stream()
                    .map(product -> {
                        EamAssetMouldProduct eamAssetMouldProduct = BeanUtil.copyProperties(product, EamAssetMouldProduct.class);
                        eamAssetMouldProductService.setDefaultValue(eamAssetMouldProduct);
                        eamAssetMouldProduct.setAssetId(item.getId());
                        return eamAssetMouldProduct;
                    }).collect(Collectors.toList());
        }

        Boolean result = super.updateById(item);
        if (result.equals(false)) throw new OptimisticLockerException();

        // 保存附件表
        EamAssetPictureQuery deleteQuery = new EamAssetPictureQuery();
        deleteQuery.setAssetId(item.getId());
        eamAssetPictureService.deleteList(deleteQuery);
        eamAssetPictureService.save(attachDTOS);

        eamCustomService.saveEamCustoms(dto.getCustoms(), item.getId(), item.getAssetKind());

        eamAssetMouldProductService.remove(Wrappers.<EamAssetMouldProduct>lambdaQuery().eq(EamAssetMouldProduct::getAssetId, item.getId()));
        if (CollUtil.isNotEmpty(products)) eamAssetMouldProductService.saveBatch(products);
    }

    /**
     * 保存资产台账
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveInfo(EamAssetInfoDTO dto) {
        if (StrUtil.isEmpty(dto.getId())) {
            // 新增
            this.insert(dto);
        } else {
            // 更新
            this.update(dto);
        }
        if (StrUtil.isNotEmpty(dto.getMouldPackageId())) {
            EamMouldPackageInfo eamMouldPackageInfo = new EamMouldPackageInfo();
            eamMouldPackageInfo.setId(dto.getMouldPackageId());
            eamMouldPackageInfo.setStatus(1);
            eamMouldPackageInfoService.updateById(eamMouldPackageInfo);
        }
        //批量更新模板框状态
        eamMouldPackageInfoService.checkUpdateStatus(dto.getMouldPackageId());
    }

    /**
     * 变更资产台账
     *
     * @param assetChangeInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeInfo(AssetChangeInfoDTO assetChangeInfo) {
        EamAssetInfo item = this.getById(assetChangeInfo.getId());
        this.changeInfo(item, assetChangeInfo);
    }

    /**
     * 变更资产台账
     *
     * @param assetChangeInfo
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeInfo(EamAssetInfo item, AssetChangeInfoDTO assetChangeInfo) {
        if (item == null || item.getDeleted() == 1) {
            throw new CustomException("资产台账不存在，更新失败");
        }
        item.setUsingDepartmentId(assetChangeInfo.getUsingDepartmentId());
        item.setUsingDepartmentName(assetChangeInfo.getUsingDepartmentName());
        item.setUsingPersonId(assetChangeInfo.getUsingPersonId());
        item.setUsingPersonName(assetChangeInfo.getUsingPersonName());
        item.setLocationId(assetChangeInfo.getLocationId());
        item.setLocationName(assetChangeInfo.getLocationName());
        item.setAssetStatus(assetChangeInfo.getAssetStatus());

        // 默认数据
        this.setDefaultValue(item);

        // 更新
        Boolean result = super.updateById(item);
        if (result.equals(false)) throw new OptimisticLockerException();
    }

    /**
     * 根据批量主键删除资产台账(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamAssetInfoDTO dto) {

        EamAssetInfo item = new EamAssetInfo();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamAssetInfo item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
    }

    /**
     * 根据主键获取资产台账信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamAssetInfoDTO get(String id) {
        // 查询数据
        EamAssetInfo item = this.baseMapper.selectById(id);
        EamAssetInfoDTO dto = new EamAssetInfoDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 根据主键获取资产台账信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamAssetInfoDTO getView(String id) {
        // 查询数据
        EamAssetInfo item = this.baseMapper.selectById(id);
        EamAssetInfoDTO dto = new EamAssetInfoDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        // 添加附件
        EamAssetPictureQuery attachQuery = new EamAssetPictureQuery();
        attachQuery.setAssetId(id);
        List<EamAssetPictureDTO> attachList = eamAssetPictureService.getList(attachQuery);

        // 设置附件
        dto.setAssetPhotos(new ArrayList<>());
        for (EamAssetPictureDTO attach : attachList) {
            SysAnnexesFileDTO fileDTO = new SysAnnexesFileDTO();
            fileDTO.setFilename(attach.getFileName());
            fileDTO.setPath(attach.getPath());
            fileDTO.setOriginalfilename(attach.getOriginalFilename());
            fileDTO.setFileType(attach.getFileType());
            fileDTO.setUrl(attach.getUrl());
            dto.getAssetPhotos().add(fileDTO);
        }
        EamAssetMouldProductQuery productQuery = new EamAssetMouldProductQuery();
        productQuery.setAssetId(item.getId());
        List<EamAssetMouldProductDTO> productList = eamAssetMouldProductService.getList(productQuery);
        dto.setProducts(productList);
        return dto;
    }


    /**
     * 根据主键获取资产台账信息
     *
     * @param code 主键
     * @return StandardCodeDTO
     */
    public EamAssetInfoDTO getInfobyCode(String code) {
        // 查询数据
        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamAssetInfo::getAssetCode, code);
        queryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
        EamAssetInfo item = this.baseMapper.selectOne(queryWrapper);

        if (item != null) {
            EamAssetInfoDTO dto = new EamAssetInfoDTO();
            try {
                BeanUtils.copyProperties(item, dto);
            } catch (RuntimeException e) {
                throw e;
            }

            // 添加附件
            EamAssetPictureQuery attachQuery = new EamAssetPictureQuery();
            attachQuery.setAssetId(item.getId());
            List<EamAssetPictureDTO> attachList = eamAssetPictureService.getList(attachQuery);

            // 设置附件
            dto.setAssetPhotos(new ArrayList<>());
            for (EamAssetPictureDTO attach : attachList) {
                SysAnnexesFileDTO fileDTO = new SysAnnexesFileDTO();
                fileDTO.setFilename(attach.getFileName());
                fileDTO.setPath(attach.getPath());
                fileDTO.setOriginalfilename(attach.getOriginalFilename());
                fileDTO.setFileType(attach.getFileType());
                fileDTO.setUrl(attach.getUrl());
                dto.getAssetPhotos().add(fileDTO);
            }

            return dto;
        }

        return null;
    }

    /**
     * 插入资产台账
     *
     * @param list 批量插入资产台账
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(List<EamAssetInfoUploadExcel> list) {

        List<EamAssetInfo> savelist = new ArrayList<>();
        list.forEach(itemOne -> {
            // 保存
            EamAssetInfo item = new EamAssetInfo();
            BeanUtils.copyProperties(itemOne, item);
            this.setDefaultValue(item);
            savelist.add(item);
        });
        // 保存
        if (savelist.size() > 0) super.saveBigBatch(savelist);
    }

    /**
     * 修改资产台账
     *
     * @param mouldCodes 批量修改资产台账
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(List<String> mouldCodes, EamAssetInfo eamAssetInfo) {

        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(EamAssetInfo::getAssetCode, mouldCodes);
        queryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
        List<EamAssetInfo> findList = super.list(queryWrapper);
        List<EamAssetInfo> saveList = findList.stream().map(itemOne -> {
            EamAssetInfo item = new EamAssetInfo();
            BeanUtils.copyProperties(itemOne, item);
            item.setLastUpdatedUserId(SecurityUtils.getUserId());
            item.setLastUpdateTime(new Date());
            item.setId(itemOne.getId());
            item.setVersion(itemOne.getVersion());
            item.setAssetStatus(eamAssetInfo.getAssetStatus());
            item.setLocationId(eamAssetInfo.getLocationId());
            item.setLocationName(eamAssetInfo.getLocationName());
            item.setStorageStatus(eamAssetInfo.getStorageStatus());
            return item;
        }).collect(Collectors.toList());
        // 保存
        if (!saveList.isEmpty()) super.updateBigBatch(saveList);
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamAssetInfoDTO>
     */
    public List<EamAssetInfoDTO> getList(EamAssetInfoQuery query) {
        // 查询条件
        QueryWrapper<EamAssetInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(query.getDeleted() != null, EamAssetInfo::getDeleted, query.getDeleted());
        qw.lambda().eq(query.getEnabled() != null, EamAssetInfo::getEnabled, query.getEnabled());
        qw.lambda().eq(query.getProcess() != null, EamAssetInfo::getProcess, query.getProcess());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetCode()), EamAssetInfo::getAssetCode, query.getAssetCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetName()), EamAssetInfo::getAssetName, query.getAssetName());
        qw.lambda().eq(query.getAssetKind() != null, EamAssetInfo::getAssetKind, query.getAssetKind());
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetTypeId()), EamAssetInfo::getAssetTypeId, query.getAssetTypeId());
        qw.lambda().eq(query.getAssetStatus() != null, EamAssetInfo::getAssetStatus, query.getAssetStatus());
        qw.lambda().eq(!StrUtil.isEmpty(query.getMakerId()), EamAssetInfo::getMakerId, query.getMakerId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getManageDepartmentName()), EamAssetInfo::getManageDepartmentName, query.getManageDepartmentName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getUsingDepartmentId()), EamAssetInfo::getUsingDepartmentId, query.getUsingDepartmentId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getLocationId()), EamAssetInfo::getLocationId, query.getLocationId());
        qw.lambda().ge(!StrUtil.isEmpty(query.getNextCheckDateStart()), EamAssetInfo::getNextCheckDate, query.getNextCheckDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getNextCheckDateEnd()), EamAssetInfo::getNextCheckDate, query.getNextCheckDateEnd());
        // 查询数据
        List<EamAssetInfo> list = super.list(qw);

        return convertList(list, EamAssetInfoDTO.class);
    }

    /**
     * 根据主键获取资产台账信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteitem(String id) {
        EamAssetInfo item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    /**
     * 根据主键获取资产台账信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public boolean updateAssetStatus(String id, Integer assetStatus) {
        EamAssetInfo item = new EamAssetInfo();
        item.setAssetStatus(assetStatus);
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return this.update(item, queryWrapper);
    }


    /**
     * 根据主键获取资产台账信息
     *
     * @param code 主键
     * @return StandardCodeDTO
     */
    public EamAssetInfoDTO getNoPicInfoByCode(String code) {
        // 查询数据
        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamAssetInfo::getAssetCode, code);
        queryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
        EamAssetInfo item = this.baseMapper.selectOne(queryWrapper);

        if (item != null) {
            EamAssetInfoDTO dto = new EamAssetInfoDTO();
            try {
                BeanUtils.copyProperties(item, dto);
            } catch (RuntimeException e) {
                throw e;
            }
            return dto;
        }

        return null;
    }

    /**
     * 新增或修改数据
     * 校验唯一规则: 企业编号+资产名称
     *
     * @param eamAssetInfoList 批量数据
     */
    @Transactional
    public void insertOrUpdateBatch(List<EamAssetInfo> eamAssetInfoList) {
        // 查询已存在的数据
        EamAssetInfoQuery query = new EamAssetInfoQuery();
        query.setEnabled(AvailableStatus.ENABLE.getValue());
        query.setDeleted(DeleteFlag.NOTDELETED.getValue());
        Function<EamAssetInfo, String> getKey = t -> t.getAssetName() + Optional.ofNullable(t.getEnterpriseCode()).orElse("");
        Map<String, EamAssetInfo> listMap = this.list(Wrappers.<EamAssetInfo>lambdaQuery()
                        .eq(EamAssetInfo::getEnabled, AvailableStatus.ENABLE.getValue())
                        .eq(EamAssetInfo::getDeleted, DeleteFlag.NOTDELETED.getValue()))
                .stream()
                .collect(Collectors.toMap(getKey, Function.identity()));
        // 过滤已存在的数据  已存在数据更新
        List<EamAssetInfo> update = eamAssetInfoList.stream()
                .filter(t -> listMap.containsKey(getKey.apply(t)))
                .peek(t -> {
                    EamAssetInfo exist = listMap.get(getKey.apply(t));
                    t.setId(exist.getId());
                    t.setAssetName(exist.getAssetName());
                    t.setCreatedUserId(exist.getCreatedUserId());
                    this.setDefaultValue(t);
                })
                .collect(Collectors.toList());
        // 过滤不存在的数据  不存在数据新增
        List<EamAssetInfo> insert = eamAssetInfoList.stream()
                .filter(t -> !listMap.containsKey(getKey.apply(t)))
                .peek(t -> {
                    this.setDefaultValue(t);
                    t.setEnabled(AvailableStatus.ENABLE.getValue());
                })
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(update)) {
            this.updateBatchById(update);
        }
        if (CollUtil.isNotEmpty(insert)) {
            this.saveBatch(insert);
        }
    }

    public EamAssetInfoDTO getInfobyMould(String code) {
        // 查询数据
        QueryWrapper<EamAssetInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamAssetInfo::getAssetCode, code);
        queryWrapper.lambda().eq(EamAssetInfo::getAssetKind, AssetKind.MOULD.getValue());
        queryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
        EamAssetInfo item = this.baseMapper.selectOne(queryWrapper);

        if (item != null) {
            EamAssetInfoDTO dto = new EamAssetInfoDTO();
            try {
                BeanUtils.copyProperties(item, dto);
            } catch (RuntimeException e) {
                throw e;
            }
            return dto;
        }

        return null;
    }

    // 通过单条产品获取模具
    public List<EamAssetInfoDTO> selectByProductId(String productId) {
        List<String> productIds = new ArrayList<>();
        productIds.add(productId);
        return convertList(this.getMouldListByProduct(productIds), EamAssetInfoDTO.class);
    }

    /**
     * 根据产品获取模具
     *
     * @param productIds 产品id列表
     * @return 模具列表
     */
    public List<EamAssetInfo> getMouldListByProduct(List<String> productIds) {
        return this.mouldAssetInfoDao.getMouldListByProduct(productIds);
    }

    /**
     * 查询产品模具信息
     * @param eamAssetInfoDTO
     * @return
     */
    public List<EamAssetInfoDTO>queryProductMould(EamAssetInfoDTO eamAssetInfoDTO){
       return this.baseMapper.queryProductMould(eamAssetInfoDTO);
    }
}

